package com.kong.consumer1.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kong.consulapi.domain.Pig;
import com.kong.consulapi.vo.BaseGenericOutputDTO;
import com.kong.consulapi.vo.BaseOutputDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author gedachao
 * @description
 * @date 2020-08-08 16:19
 */
@RestController
public class ControllerDemo {

    @Autowired
    RestTemplate restTemplate;

    @PostMapping("/hi")
    public String test1() {
        String url = "http://" + "consul-provider1/test/hello";
        String res = restTemplate.postForObject(url, null, String.class);
        System.out.println("结果为：" + res);
        return res;
    }

    @PostMapping("/getList1")
    public void getList1() {
        String url = "http://consul-provider1/test/getList";
        ParameterizedTypeReference<BaseOutputDTO> typeReference = new ParameterizedTypeReference<BaseOutputDTO>() {
        };
        ResponseEntity<BaseOutputDTO> entity = restTemplate.exchange(url, HttpMethod.GET, null, typeReference);
        BaseOutputDTO body = entity.getBody();
        System.out.println(body);

    }

    @PostMapping("/getList")
    public void getList() {
        String url = "http://consul-provider1/test/getList";
        BaseOutputDTO baseOutputDTO = restTemplate.getForObject(url, BaseOutputDTO.class);
        List<Map> resList = (List<Map>) baseOutputDTO.getResponseBody();
        ArrayList<Pig> pigs = new ArrayList<>();
        for (Map map : resList) {
            Pig pig = JSONObject.toJavaObject((JSONObject) JSON.toJSON(map), Pig.class);
            pigs.add(pig);
        }
        System.out.println("aaa");
    }

    @PostMapping("/getGenericList")
    public void getGenericList() {
        String url = "http://consul-provider1/test/getGenericList";
        ParameterizedTypeReference<BaseGenericOutputDTO<List<Pig>>> typeReference = new ParameterizedTypeReference<BaseGenericOutputDTO<List<Pig>>>() {
        };
        ResponseEntity<BaseGenericOutputDTO<List<Pig>>> entity = restTemplate.exchange(url, HttpMethod.GET, null, typeReference);
        BaseGenericOutputDTO<List<Pig>> body = entity.getBody();
        System.out.println(body);
    }
}
